package com.ruoyi.costumeShop.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.costumeShop.domain.Costume;
import com.ruoyi.costumeShop.domain.CostumeCategory;
import com.ruoyi.costumeShop.domain.CostumeSaleOrder;
import com.ruoyi.costumeShop.domain.SaleOrderCostume;
import com.ruoyi.costumeShop.mapper.CostumeCategoryMapper;
import com.ruoyi.costumeShop.mapper.CostumeMapper;
import com.ruoyi.costumeShop.mapper.CostumeSaleOrderMapper;
import com.ruoyi.costumeShop.mapper.SaleOrderCostumeMapper;
import com.ruoyi.costumeShop.service.ISaleOrderCostumeService;
import com.ruoyi.costumeShop.vo.DashBoardVO;
import com.ruoyi.costumeShop.vo.InputVO;
import com.ruoyi.costumeShop.vo.OrderVO;
import com.ruoyi.costumeShop.vo.SaleOrderCostumeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SaleOrderCostumeServiceImpl implements ISaleOrderCostumeService {
    @Resource
    private SaleOrderCostumeMapper saleOrderCostumeMapper;
    @Autowired
    private CostumeSaleOrderMapper orderMapper;
    @Autowired
    private CostumeCategoryMapper categoryMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CostumeMapper costumeMapper;

    /**
     * 生成已销售的系列数量报表饼图，按类别统计销量
     */
    @Override
    public List<DashBoardVO> countByCategoryId() {
        List<CostumeCategory> categoryList = this.categoryMapper.queryAll(new CostumeCategory());
        List<DashBoardVO> dashBoardList = new ArrayList<>();
        for (CostumeCategory posCategory : categoryList) {
            DashBoardVO dashBoardVO = new DashBoardVO();
            //根据系列id查询已销售数据的销售量
            List<Integer> integers = this.saleOrderCostumeMapper.countByCategoryIdList(posCategory.getCostumeCategoryId());
            System.out.print(integers+";");
            int count =0;
            //使相同系列下的所有产品销量相加
            for (Integer integer : integers) {
                count+=integer;
            }
            String name = posCategory.getCostumeCategoryName();
            dashBoardVO.setName(name);
            dashBoardVO.setValue(count);
            dashBoardList.add(dashBoardVO);
        }
        return dashBoardList;
    }

    /**
     * 创建订单Costume
     */
    public InputVO createOrder(){
        String orderNumber = "NO"+ DateUtils.dateTimeNow()+(int)Math.random();
        ArrayList<SaleOrderCostumeVO> orderCostumeVOList = new ArrayList<>();
        redisTemplate.opsForList().rightPush(orderNumber,orderCostumeVOList);
        System.out.println("订单号为"+orderNumber);
        InputVO inputVO = new InputVO();
        inputVO.setOrderNo(orderNumber);
        return inputVO;
    }

    /**
     * 提交订单操作
     */
    @Override
    public Boolean commitOrder(OrderVO orderVO) {
        boolean committable = true;
        String orderNo = orderVO.getOrderNo();
        //遍历列表里面的orderItemVo，对每一个商品判断库存是否足够
        //使用fastjson字符串转换
        String cachelistString= JSONObject.toJSONString(redisTemplate.opsForList().range(orderNo,0,-1), SerializerFeature.WriteClassName);
        List<SaleOrderCostumeVO> cacheOrderItemlist = JSONObject.parseArray(cachelistString, SaleOrderCostumeVO.class);
        //从缓存中的商品一一判断是否库存足够
        for (SaleOrderCostumeVO orderItemVO : cacheOrderItemlist) {
            if(orderItemVO==null)
                continue;
            Costume posItem = costumeMapper.queryByItemNoAndSize(orderItemVO.getCostumeNo(),orderItemVO.getSize());//--------------*****
            //若库存不足则返回false
            if(posItem.getCostumeInventory()<orderItemVO.getQuantity()){
                committable = false;
                return false;
            }
        }
        //如果库存不够则设置flag，方法返回操作失败的false
        if(committable){
            //插入order表生成orderid，将缓存中的OrderVo对象插入到order表中，
            CostumeSaleOrder costumeSaleOrder = new CostumeSaleOrder();
            System.out.println(orderVO.getOrderNo());//------------------------*************
            costumeSaleOrder.setSaleOrderNo(orderNo);
            costumeSaleOrder.setSaleTotalAmount(orderVO.getTotalAmount());
            costumeSaleOrder.setSaleTime(DateUtils.getNowDate());
            costumeSaleOrder.setSaleTotalQuantity(orderVO.getTotalQuantity());
            orderMapper.insertCostumeSaleOrder(costumeSaleOrder);
            Long orderId = orderMapper.queryOrderByOrderNo(orderNo).getSaleOrderId();
            // 1）则将缓存中的列表数据插入到saleOrderCostume表中，更新costume表中的库存
            for (SaleOrderCostumeVO saleOrderCostumeVO : cacheOrderItemlist) {
                if(saleOrderCostumeVO==null)
                    continue;
                Costume costume = costumeMapper.queryByItemNoAndSize(saleOrderCostumeVO.getCostumeNo(),saleOrderCostumeVO.getSize());//----------------------*************
                //插入记录到saleOrderCostume表中
                SaleOrderCostume saleOrderCostume = new SaleOrderCostume();
                saleOrderCostume.setOrderId(orderId);
                saleOrderCostume.setCostumeId(costume.getCostumeId());
                saleOrderCostume.setSizeId(costume.getSizeId());
                saleOrderCostume.setSalePrice(SaleOrderCostumeVO.getSalePrice());
                saleOrderCostume.setQuantity(saleOrderCostumeVO.getQuantity());
                saleOrderCostumeMapper.insert(saleOrderCostume);
                //更新item表中原有的库存
                costume.setCostumeInventory(costume.getCostumeInventory()-saleOrderCostumeVO.getQuantity());
                costumeMapper.updateCostume(costume);
            }
            //清空redis缓存中的ordervo和orderitemvo的key，value
            redisTemplate.delete(orderNo);
        }
        return true;
    }


    /**
     * 查询当前缓存中的订单状态，在输入itemNo同时更新当前订单状态
     */
    public OrderVO getCurrentOrderVo(String orderNo){
        OrderVO orderVO = new OrderVO();
        orderVO.setOrderNo(orderNo);
        orderVO.setSaleTime(DateUtils.getNowDate());
        Long totalQuantity = Long.valueOf(0);
        BigDecimal totalAmount = BigDecimal.valueOf(0);
        String cachelist= JSONObject.toJSONString(redisTemplate.opsForList().range(orderNo,0,-1), SerializerFeature.WriteClassName);
        List<SaleOrderCostumeVO> cacheOrderItemlist = JSONObject.parseArray(cachelist, SaleOrderCostumeVO.class);
        for (SaleOrderCostumeVO orderItemVO : cacheOrderItemlist) {
            if(orderItemVO==null)
                break;
            totalQuantity += orderItemVO.getQuantity();
            totalAmount = BigDecimal.valueOf(totalAmount.floatValue() + orderItemVO.getQuantity() * orderItemVO.getSalePrice().floatValue());
        }
        orderVO.setTotalAmount(totalAmount);
        orderVO.setTotalQuantity(totalQuantity);
        return orderVO;
    }

    /**
     * @Description  根据商品编号，将商品插入待下单的订单明细集合
//     * @param itemNo---------------------------------------------------------------//
     */
    @Override
    public Map<String, Object> enterLineOrderItemVO(InputVO inputVO) {
        System.out.println("---------debug---------开始执行方法");
        //如果机器第一次录入商品，则创建一个订单缓存，生成订单no，放置redis缓存中，并更改判断变量为false
        //根据itemIo查询到item，将item中的编号、名称、价格属性取出来
        //new一个OrderItemVO对象，将编号、名称、价格属性set到Vo中
        String itemNo = inputVO.getCostumeNo();
        String orderNo = inputVO.getOrderNo();
        String size = inputVO.getSize(); //--------------*****尺码
        Costume costume = costumeMapper.queryByItemNoAndSize(itemNo,size);//-----------------*****
//        System.out.println(costume.toString());
        //取出订单中的所有商品列表
//        List<OrderItemVO> cacheOrderItemVOList = (List<OrderItemVO>) redisTemplate.opsForList().range(orderNo,0,-1);
        String cacheOrderItemVOString= JSONObject.toJSONString(redisTemplate.opsForList().range(orderNo,0,-1), SerializerFeature.WriteClassName);
        List<SaleOrderCostumeVO> cacheOrderItemVOList = JSONObject.parseArray(cacheOrderItemVOString, SaleOrderCostumeVO.class);
        System.out.println("---------debug---------取出订单中的所有商品列表");
        boolean flag = true;
        //如果当前录入的商品已在购物车当中，则在缓存中的该商品数量加一
        for (SaleOrderCostumeVO orderItemVO : cacheOrderItemVOList) {
            int i = 0;
            if(orderItemVO == null){
                break;
            }
            System.out.println(costume.getCostumeNo());
            System.out.println(orderItemVO.getCostumeNo());
            if(costume.getCostumeNo().equals(orderItemVO.getCostumeNo())&&costume.getSize().equals(orderItemVO.getSize())){
                orderItemVO.setQuantity(orderItemVO.getQuantity()+1);
                redisTemplate.opsForList().set(orderNo,i,orderItemVO);
                flag = false;
                break;
            }
            i++;
        }
        //如果该商品没在购物车中，是一个新商品，则设置数量为1，并将该商品加入缓存中
        if(flag){
            SaleOrderCostumeVO orderItemVO = new SaleOrderCostumeVO();
            orderItemVO.setCostumeNo(itemNo);
            orderItemVO.setCostumeName(costume.getCostumeName());
            orderItemVO.setSalePrice(costume.getCostumePrice());
            orderItemVO.setQuantity(1L);
            orderItemVO.setSize(costume.getSize());//------------------------******
            redisTemplate.opsForList().leftPush(orderNo,orderItemVO);
        }
        OrderVO currentOrderVo = this.getCurrentOrderVo(orderNo);
        HashMap<String, Object> info = new HashMap<>();
        //转换json
        String returnString= JSONObject.toJSONString(redisTemplate.opsForList().range(orderNo,0,-1), SerializerFeature.WriteClassName);
        List<SaleOrderCostumeVO> returnOrderItemList = JSONObject.parseArray(returnString, SaleOrderCostumeVO.class);
        //System.out.print("returnOrderItemList:::"+returnOrderItemList);
        //返回当前购物车列表
        info.put("orderCostumeList",returnOrderItemList);
        //返回当前订单状态
        info.put("currentOrderVo",currentOrderVo);
        return info;
    }


    /**
     * 通过ID查询单条数据
     * @param orderItemId 主键
     * @return 实例对象
     */
    @Override
    public SaleOrderCostume queryById(Long orderItemId) {
        return this.saleOrderCostumeMapper.queryById(orderItemId);
    }

    /**
     * 查询指定行
     *
     * @param orderItem 筛选条件
     * @return 查询结果
     */
    @Override
    public List<SaleOrderCostume> queryAll(SaleOrderCostume orderItem) {
        return this.saleOrderCostumeMapper.queryAll(orderItem);
    }

    /**
     * 新增数据
     *
     * @param orderItem 实例对象
     * @return 实例对象
     */
    @Override
    public SaleOrderCostume insert(SaleOrderCostume orderItem) {
        this.saleOrderCostumeMapper.insert(orderItem);
        return orderItem;
    }

    /**
     * 修改数据
     *
     * @param orderItem 实例对象
     * @return 实例对象
     */
    @Override
    public SaleOrderCostume update(SaleOrderCostume orderItem) {
        this.saleOrderCostumeMapper.update(orderItem);
        return this.queryById(orderItem.getOrderCostumeId());
    }

    /**
     * 通过主键删除数据
     *
     * @param orderItemId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long orderItemId) {
        return this.saleOrderCostumeMapper.deleteById(orderItemId) > 0;
    }

}
